#include "configurationdialog.h"
#include "ui_configurationdialog.h"

#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
#include <QPainter>

ConfigurationDialog::ConfigurationDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ConfigurationDialog),
    _loadAnimation(qApp->applicationDirPath() + "/Load.gif")
{
    ui->setupUi(this);

    connect(ui->testButton, SIGNAL(clicked()), this, SLOT(onTest()));
    connect(&_loadAnimation, SIGNAL(frameChanged(int)),    this,    SLOT(paintNewFrame(int)));
    _isLoad = true;
}


void ConfigurationDialog::paintEvent(QPaintEvent *event)
{

   if(_isLoad)
   {
       // First we extract the current frame
       QPixmap currentFrame = _loadAnimation.currentPixmap();

       QRect frameRect = currentFrame.rect();

       // Only redraw when the frame is in the invalidated area
       frameRect.moveCenter(rect().center());
       if (frameRect.intersects(event->rect()))
       {
          QPainter painter(this);
          painter.drawPixmap(
             frameRect.left(),
             frameRect.top(),
             currentFrame);
       }
   }
}

void ConfigurationDialog::paintNewFrame(int)
{
   repaint();
}


ConfigurationDialog::~ConfigurationDialog()
{
    delete ui;
}

void ConfigurationDialog::onTest()
{
    _isLoad = true;
    _loadAnimation.start();
    if(!_testConnection())
        QMessageBox::warning(this, "Connection failed!", dbConnect->getDb().lastError().text());
    else
        QMessageBox::warning(this, "Connection successful", "Connection successful!");
    _loadAnimation.stop();
    _isLoad = false;
}


void ConfigurationDialog::setSettings(QSharedPointer <Settings> __settings)
{
    settings = __settings;
    _fillInputsBySettings();
}

void ConfigurationDialog::setDbConnection(QSharedPointer <DbConnection> __dbConnect)
{
    dbConnect = __dbConnect;
}

void ConfigurationDialog::_fillInputsBySettings()
{
    ui->hostname->setText(settings->hostname);
    ui->dbname->setText(settings->dbname);
    ui->login->setText(settings->login);
    ui->password->setText(settings->password);
}

bool ConfigurationDialog::_testConnection()
{
    settings->hostname = ui->hostname->text();
    settings->dbname = ui->dbname->text();
    settings->login = ui->login->text();
    settings->password = ui->password->text();

    if(!dbConnect->setupConnection(settings))
    {
        return false;
    }
    return true;
}

void ConfigurationDialog::done(int r)
{
    if(QDialog::Accepted == r)  // ok was pressed
    {
        if(_testConnection())
        {
            QDialog::done(r);
            settings->save();
            return;
        }
        else
        {
            QMessageBox::warning(this, "Connection failed!", dbConnect->getDb().lastError().text());
            settings->load();
            return;
        }
    }
    else    // cancel, close or exc was pressed
    {
        QDialog::done(r);
        settings->load();
        return;
    }
}
